#include "../include/ArrayList.h"
//
// Created by 冷月祭诗魂 on 2025/4/23.
//
template<typename E>
ArrayList<E>::ArrayList() {
    this->capacity = 16;
    this->_size = 0;
    this->elementData = new E[capacity];
}

template<typename E>
bool ArrayList<E>::add(E& e) {
    if (_size>=capacity) {
        int32_t newCapacity = 2*capacity;
        E* newElementData = new E[newCapacity];
        if (nullptr!=elementData) {
            for(int i = 0; i < _size; i++) {
                newElementData[i] = std::move(elementData[i]);  // 调用每个元素的拷贝赋值运算符
            }
            delete[] elementData;
        }
        capacity = newCapacity;
        elementData = newElementData;
    }
    elementData[_size++] = e;
    return true;
}

template<typename E>
bool ArrayList<E>::add(E &&e) {
    return this->add(e);
}


template<typename E>
int32_t ArrayList<E>::size() {
    return _size;
}

template<typename E>
bool ArrayList<E>::isEmpty() {
    return _size==0;
}

template<typename E>
E ArrayList<E>::get(int32_t index) {
    if (index<0 || index>=_size) {
        throw  IndexOutOfBoundsException("index " + std::to_string(index) +
                              " is out of bounds for size " +
                              std::to_string(_size));
    }
    E e = std::move(elementData[index]);
    return e;
}


template<typename E>
E ArrayList<E>::remove(int32_t index) {
    if (index<0||index>=_size) {
        throw  IndexOutOfBoundsException("index " + std::to_string(index) +
                              " is out of bounds for size " +
                              std::to_string(_size));
    }
    E e = std::move(elementData[index]);
    for (int32_t i=index+1;i<_size;i++) {
        elementData[i-1] = elementData[i];
    }
    _size--;
    return e;
}

template<typename E>
ArrayList<E>::~ArrayList() {
    delete[] elementData;
}

